import React, { Component } from 'react'
import { Pagination, Input } from 'antd'
import './search.less'
import MyEmpty from '../../components/myempty'
import TopNav from '../top_nav'
import BottomBar from '../bottom_bar'
import SearchItem from './search_item'
import searchApi from '../../api/search'
import parseUrl from '../../utils/parseUrl'
export default class Home extends Component {
  state = {
    searchList: [],
    key: '',
    total: 0,
    pageNum: 1,
    pageSize: 10
  }

  componentDidMount() {
    this.setState({
      key:parseUrl(decodeURI(this.props.history.location.search)).key
    })
    this.handleSearch(parseUrl(decodeURI(this.props.history.location.search)).key, this.state.pageNum, this.state.pageSize)
  }

  handleSearch = (key, pageNum, pageSize) => {
    searchApi.list({ key, pageNum, pageSize }).then(res => {
      if (res.success) {
        this.setState({
          searchList: res.data.data,
          total: res.data.total * 1
        })
      }
    }).catch(err => {
      console.log(err);
    })
  }
  onPageChange = (current, pageSize) => {
    this.handleSearch(this.state.key, current, pageSize)
  }
  searchAll = (key) => {
    this.setState({
      key
    })
    this.handleSearch(key, 1, this.state.pageSize);
  }
  render() {
    const { searchList, pageNum, total } = this.state
    return (
      <div className="search-container">
        <TopNav style={{ background: '#fff', color: '#666' }} active="/home" />
        <div className="content">
          <div className="content-main">
            <div className="top-search">
              <img src="https://gulimall-jia.oss-cn-beijing.aliyuncs.com/search_logo.jpg" alt="search" />
              <div className="search-box">
                <Input.Search defaultValue={parseUrl(decodeURI(this.props.history.location.search)).key} placeholder="输入关键词搜索" onSearch={this.searchAll} enterButton />
              </div>
            </div>
            {
              searchList.length ? searchList.map(item => {
                return <SearchItem key={item.id + item.searchType} {...item} />
              }) : <MyEmpty content="没有找到内容" />
            }
          </div>
          <div className="page-box">
            <Pagination
              onChange={this.onPageChange}
              defaultCurrent={pageNum}
              total={total}
            />
          </div>
        </div>
        <BottomBar style={{ background: '#f9f9f9', borderTop: '1px solid #e5e5e5' }} />
      </div>
    )
  }
}

